﻿using System.Text.Json;
using System.Text.Json.Serialization;

namespace FrameworkCore.Converters;
public class BigIntegerConverter : JsonConverter<long>
{
    public override long Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        switch (reader.TokenType)
        {
            case JsonTokenType.String:
                // 尝试将字符串解析为 long 值
                if (long.TryParse(reader.GetString(), out var longValue))
                {
                    return longValue;
                }
                throw new JsonException("Invalid string format for long value.");

            case JsonTokenType.Number:
                // 从数字令牌中读取 long 值
                return reader.GetInt64();

            default:
                throw new JsonException($"Unexpected token type: {reader.TokenType}");
        }
    }

    public override void Write(Utf8JsonWriter writer, long value, JsonSerializerOptions options)
    {
        // 将 long 值转换为字符串并写入 JSON
        writer.WriteStringValue(value.ToString());
    }
}
